﻿using EmoneyWeiXinCommon;
using EmoneyWeiXinDAL;
using EmoneyWeiXinEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EmoneyWeiXinBLL
{
    public class WeiXinReplyRule
    {

        /// <summary>
        /// 今日提示 财富早九点
        /// </summary>
        /// <returns></returns>
        public string JinRiTiShis(string fromUserName, string toUserName)
        {
            try
            {
                Vm_Dms_GetnewsbycodeBLL bll = new Vm_Dms_GetnewsbycodeBLL();
                string str = "影响今日股市的利好与利空消息";
                //string picurl = "http://ds.emoney.cn/weixin/images/weather/w" + we.weather + ".jpg";
                string picurl = "http://down.emoney.cn/images/float/images/lhpklk.png";
                string pointurl = Config.DSChaoguquanUrl + "point.aspx";
                StringBuilder sb = new StringBuilder();
                sb.Append("<xml>");
                sb.Append("<ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>");
                sb.Append("<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>");
                sb.Append("<CreateTime>" + StringTools.ConvertDateTimeInt(DateTime.Now) + "</CreateTime>");
                sb.Append("<MsgType><![CDATA[news]]></MsgType>");
                sb.Append("<ArticleCount>1</ArticleCount>");
                sb.Append("<Articles>");
                sb.Append("<item>");
                sb.Append("<Title><![CDATA[" + str + "]]></Title> ");
                sb.Append("<Description><![CDATA[" + bll.GetLHMsg() + "]]></Description>");
                sb.Append("<PicUrl><![CDATA[" + picurl + "]]></PicUrl>");
                sb.Append("<Url><![CDATA[" + pointurl + "]]></Url>");
                sb.Append("</item>");
                sb.Append("</Articles>");
                sb.Append("<FuncFlag>0</FuncFlag>");
                sb.Append("</xml> ");
                return sb.ToString();
            }
            catch (Exception ex)
            {
                StringTools.GetSendMail("WeiXinReplyRule.JinRiTiShis:" + ex.Message);
                return "";
            }
        }

        public string gotoService(string fromUser, string toUser,string weixinId)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<xml>");
            sb.Append("<ToUserName><![CDATA[" + toUser + "]]></ToUserName>");
            sb.Append("<FromUserName><![CDATA[" + fromUser + "]]></FromUserName>");
            sb.Append("<CreateTime>" + DateTime.Now.Ticks.ToString() + "</CreateTime>");
            sb.Append("<MsgType><![CDATA[transfer_customer_service]]></MsgType>");
            // string twocodeval = "";
            try
            {
                //string kfIds = Config.KfIds;
                //string[] kfIdarry = Config.KfIds.Split(',');
                //Random rand = new Random();
                //int index = rand.Next(kfIdarry.Length); //随机一个客服ID
                //string tempKfId = kfIdarry[index];
                //WeiXinApiBLL wxbll = new WeiXinApiBLL();
                //var b = wxbll.IsReachAccept(tempKfId,weixinId);
                //if (!b)
                //{
                //    sb.Append("<TransInfo>");
                //    sb.Append("<KfAccount>" + tempKfId + "</KfAccount>");
                //    sb.Append("</TransInfo>");
                  
                //}

                //bool bl = true;
                //通过openeid获取twocodeval
                //WxuserBLL1 wb = new WxuserBLL1();
                //var wxuser = wb.getWxUser(toUser);
                //if (wxuser != null)
                //{
                //    twocodeval = wxuser.tcode.ToString();
                //    var ds = TwoCodeManager.searchToCodeInfoByParmval(twocodeval);
                //    if (ds != null && ds.Tables.Count > 0)
                //    {
                //        var table = ds.Tables[0];
                //        if (table != null && table.Rows.Count > 0)
                //        {
                //            var kf_account = table.Rows[0]["kf_id"];
                //            if (kf_account != null && kf_account.ToString() != "")
                //            {
                //                //MyTrace.get().add("goto6" + kf_account);
                //                //需要验证客服接入最大值
                //                WeiXinApiBLL wxbll = new WeiXinApiBLL();
                //                var b = wxbll.IsReachAccept(kf_account.ToString());
                //                if (!b)
                //                {
                //                    sb.Append("<TransInfo>");
                //                    sb.Append("<KfAccount>" + kf_account.ToString() + "</KfAccount>");
                //                    sb.Append("</TransInfo>");
                //                    // bl = false;
                //                }
                //            }
                //        }
                //    }
                //}

                //if (bl)
                //{
                //    MyTrace.get().add("goto77:Start-getRandomKFString");
                //    var ss = getRandomKFString();
                //    if (!string.IsNullOrEmpty(ss))
                //        sb.Append(ss);
                //}
            }
            catch (Exception)
            {

            }
            sb.Append("</xml>");
            return sb.ToString();
        }

        public static string getReply(string fromUser, string toUser, string reply)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<?xml version=\"1.0\" encoding=\"gbk\"?>");
            sb.Append("<xml>");
            sb.Append(string.Format("<ToUserName>{0}</ToUserName>", fromUser));
            sb.Append(string.Format("<FromUserName>{0}</FromUserName>", toUser));
            sb.Append(string.Format("<CreateTime>{0}</CreateTime>", DateTime.Now.Ticks.ToString()));
            sb.Append(string.Format("<MsgType>text</MsgType>"));
            sb.Append(string.Format("<Content><![CDATA[{0}]]></Content>", reply));
            sb.Append("</xml>");
            return sb.ToString();
        }

        public List<Security> GetAllStocks()
        {
            string key = "EMoney.WeiXin.BLL.WeiXinReplyBLL.GetAllStock1";
            List<Security> lst = null;
            MemcachedTools1 Cache = new MemcachedTools1();
            lst = Cache.Get<List<Security>>(key);
            if (lst == null)
            {
                SecurityDAL dal = new SecurityDAL();
                lst = dal.GetAllStocks();
                foreach (var c in lst)
                {
                    c.SecuName = c.SecuName.Replace(" ", "");
                    c.SecuCode = c.SecuCode.Replace(" ", "");
                }
                Cache.Add(key, lst, 6, 0, 0);
            }
            return lst;
        }

        public string getKeyWordReply(string content, string fromUser, string toUser)
        {
            content = content.ToLower().Trim();
            IList<KeyWordModel> list = KeyWordBLL.getKeyWordForMatch();
            KeyWordModel obj = null;
            for (int i = 0; i < list.Count; i++)
            {
                switch (list[i].conType)
                {
                    case 1://全匹配
                        if (list[i].key.ToLower() == content)
                            obj = list[i];
                        break;
                    case 2://前匹配
                        if (content.StartsWith(list[i].key.ToLower()))
                            obj = list[i];
                        break;
                    case 3://后匹配
                        if (content.EndsWith(list[i].key.ToLower()))
                            obj = list[i];
                        break;
                    case 4:
                        if (content.IndexOf(list[i].key.ToLower()) != -1)
                            obj = list[i];
                        break;
                    default: break;
                }
                if (obj != null) break;
            }
            string rp = "";
            if (obj != null)
            {
                if (obj.replyType == 1)
                {//文本回复
                    if (obj.reply.Trim() != "")
                        rp = WeiXinReplyRule.getReply(fromUser, toUser, obj.reply);
                }
                else if (obj.replyType == 2)
                {
                    //图文回复
                    NewsBLL bll = new NewsBLL();
                    NewsEntity news = bll.getNewsInfo(obj.reply);
                    if (news != null)
                    {
                        if (news.OutsideUrl != "")
                            rp = getSingleContentWithPicAndTxt(fromUser, toUser, news.title, news.Summary, news.ImageUrl, news.OutsideUrl);
                        else
                            rp = getSingleContentWithPicAndTxt(fromUser, toUser, news.title, news.Summary, news.ImageUrl, Config.Host_Url + "News/Content?openid=" + fromUser + "&nid=" + news.nid);
                    }
                }
            }
            return rp;
        }

        public string getSingleContentWithPicAndTxt(string fromUser, string toUser, string title, string summary, string imgurl, string link)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("<xml>");
            sb.AppendFormat("<ToUserName><![CDATA[" + fromUser + "]]></ToUserName>");
            sb.AppendFormat("<FromUserName><![CDATA[" + toUser + "]]></FromUserName>");
            sb.AppendFormat("<CreateTime>" + DateTime.Now.Ticks.ToString() + "</CreateTime>");
            sb.AppendFormat("<MsgType><![CDATA[news]]></MsgType>");
            sb.AppendFormat("<ArticleCount>1</ArticleCount>");
            sb.AppendFormat("<Articles>");
            sb.AppendFormat("<item>");
            sb.AppendFormat("<Title><![CDATA[" + title + "]]></Title> ");
            sb.AppendFormat("<Description><![CDATA[" + summary + "]]></Description>");
            sb.AppendFormat("<PicUrl><![CDATA[" + imgurl + "]]></PicUrl>");
            sb.AppendFormat("<Url><![CDATA[" + link + "]]></Url>");
            sb.AppendFormat("</item>");
            sb.AppendFormat("</Articles>");
            sb.AppendFormat("</xml> ");
            return sb.ToString();
        }

        /// <summary>
        /// 获取手机抽奖信息
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="fromUser"></param>
        /// <param name="toUser"></param>
        /// <returns></returns>
        public string getWinSJ(string mobile, string fromUser, string toUser, int activetype)
        {
            WinActionBLL bll = new WinActionBLL();
            List<NewsEntity> news = bll.getWinSJ(mobile, activetype);
            NewsEntity item;
            int len = news.Count; if (len > 10) len = 10;
            if (len > 0)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("<xml>");
                sb.AppendFormat("<ToUserName><![CDATA[" + fromUser + "]]></ToUserName>");
                sb.AppendFormat("<FromUserName><![CDATA[" + toUser + "]]></FromUserName>");
                sb.AppendFormat("<CreateTime>" + DateTime.Now.Ticks.ToString() + "</CreateTime>");
                sb.AppendFormat("<MsgType><![CDATA[news]]></MsgType>");
                sb.AppendFormat("<ArticleCount>" + len + "</ArticleCount>");
                sb.AppendFormat("<Articles>");
                for (int i = 0; i < len; i++)
                {
                    item = news[i];
                    sb.AppendFormat("<item>");
                    sb.AppendFormat("<Title><![CDATA[" + item.title + "]]></Title> ");
                    sb.AppendFormat("<Description><![CDATA[" + item.Summary + "]]></Description>");
                    sb.AppendFormat("<PicUrl><![CDATA[" + item.ImageUrl + "]]></PicUrl>");
                    sb.AppendFormat("<Url><![CDATA[" + Config.Host_Url + "News/Content?openid=" + fromUser + "&nid=" + item.nid + "]]></Url>");
                    sb.AppendFormat("</item>");
                }
                sb.AppendFormat("</Articles>");
                sb.AppendFormat("</xml> ");
                return sb.ToString();
            } return "0";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="stock"></param>
        /// <returns></returns>
        public List<Security> GetOne(string stock)
        {
            try
            {
                stock = stock.Replace(" ", "");
                return GetAllStocks().Where(x => x.SecuCode.Contains(stock) || x.SecuName.Contains(stock)).ToList();
            }
            catch (Exception)
            {
                return null;
            }
        }

        public string getGGHF_doctor(string stockCode, string fromUser, string toUser)
        {
            try
            {
                List<ZouShiEntity11> list = new List<ZouShiEntity11>();
                ZouShiBll zbll = new ZouShiBll();
                list = zbll.GetList11(stockCode);  //根据股票代码或者股票简码获取走势（从股票医生提供的接口取出）
                string strhtml = "";
                if (list != null)
                {
                    try
                    {
                        strhtml = list[0].Root[0].Top[0].Data[0].Summarize;
                    }
                    catch (Exception)
                    {
                        strhtml = "";
                    }
                }
                //MyTrace.get().add("getGGHF_doctor.1<" + strhtml + ">");
                StringBuilder sb = new StringBuilder();
                GPYSBLL bll = new GPYSBLL();
                string strhtml2 = "";
                var code = GetOne(stockCode);

                if (code != null && code.Count > 0)
                {
                    //评级
                    //MyTrace.get().add("getGGHF_doctor.13<" + stockCode.ToString() + ">");
                    string sdstockscoreex = bll.Getsdstockscoreex(stockCode);
                    string[] str = sdstockscoreex.Split(',');
                    sdstockscoreex = str[9].ToString();
                    StockRule rule = new StockRule(stockCode);
                    string code7 = rule.Convert7StockString(stockCode);
                    //pgfirst_y+code7         	体检综述
                    var pgfirst_y = bll.Getpgfirst_y(code7);
                    strhtml2 = code[0].SecuName + "体检评级:" + sdstockscoreex + "   ";
                    strhtml2 += pgfirst_y[0].root[0].top[0].data[0].HowToDo + "\n";
                    //MyTrace.get().add("getGGHF_doctor.18<" + strhtml2 + ">");
                }
                string url = "http://m.emoney.cn/sosoSD/test_pub.html?sc=" + stockCode + "&returnf=1";
                //MyTrace.get().add("getGGHF_doctor.2<" + strhtml2 + ">");
                if (stockCode.StartsWith("6"))
                {
                    stockCode = "sh" + stockCode;
                }
                else
                {
                    stockCode = "sz" + stockCode;
                }
                string PicUrl = "http://static.emoney.cn/sixangle/SOSO_SixAngle_" + stockCode + ".PNG?r=" + DateTime.Now.ToString("yyyyMMddHHMM") + "";
                string resxml = "";
                if (strhtml != null && strhtml != "" && strhtml2 != null && strhtml2 != "")
                {
                    resxml = "<xml><ToUserName><![CDATA[" + fromUser + "]]></ToUserName><FromUserName><![CDATA[" + toUser + "]]></FromUserName><CreateTime>" + StringTools.ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[news]]></MsgType><Content><![CDATA[" + strhtml + "]]></Content><ArticleCount>1</ArticleCount><Articles>";
                    resxml += "<item><Title><![CDATA[" + strhtml2 + "]]></Title><Description><![CDATA[" + strhtml + "]]></Description><PicUrl><![CDATA[" + PicUrl + "]]></PicUrl><Url><![CDATA[" + url + "]]></Url></item>";
                    resxml += "</Articles><FuncFlag>1</FuncFlag></xml>";
                    return resxml;
                }
                else
                {
                    return "";
                }
            }
            catch (Exception)
            {
                return "";
            }
        }
    }
}
